﻿using FRMS.DAL;
using FRMS.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using System.Drawing;
using System.Net.Http;
using System.Net.Http.Headers;
using FRMS_N71SP.Model;
using System.Text;
using FRMS.WebSockets;
using System.Reflection;
using Aspose.Cells.Charts;
using Google.Protobuf.WellKnownTypes;

namespace FRMS.BUS
{
    public class VoucherBUS
    {
        public string DeviceIp = string.Empty;
        public VoucherBUS()
        {
        }

        public ResponseMessage AddVoucher(VoucherInfo voucherInfo, string wwwroot)
        {
            ModbusRtu modbus = new ModbusRtu();
            DeviceDAL deviceDAL = new DeviceDAL();
            ResponseMessage message = new ResponseMessage();
            VoucherDAL da = new VoucherDAL();
            OwnerDAL ownerDAL = new OwnerDAL();
            OwnerInfo ownerInfo = ownerDAL.LoadOwnerInfo(voucherInfo.OwnerID);
            List<OwnerInfo> list = ownerDAL.QueryOwnerByPID(ownerInfo.ID);
            DeviceInfo deviceInfo = deviceDAL.LoadDeviceInfo(voucherInfo.DeviceID);
            int auditid = ownerDAL.QueryOwnerAudit(voucherInfo.OwnerID);
            voucherInfo.DeviceNO = deviceInfo.DeviceNO;
            string phyfloor = string.Empty;
            voucherInfo.PicturePath = ownerInfo.PicturePath;
            voucherInfo.OwnerName = ownerInfo.OwnerName;
            if (auditid > 0)
            {
                voucherInfo.QRCodeFlag = 1;
            }
            if (voucherInfo.OwnerType == 2)
            {
                voucherInfo.AuthData = modbus.GetCallAdminCmd(ownerInfo.UUID);
            }
            else
            {
                phyfloor = SortFloor(voucherInfo.AuthorizedFloor, voucherInfo.FloorInfo, voucherInfo.pFloorInfo);

                voucherInfo.AuthData = modbus.GetCallCmd(phyfloor, ownerInfo.UUID);
            }
            //查询该设备下，该业主主卡及副卡凭证信息
            Dictionary<int, VoucherInfo> vouvher_dic = new Dictionary<int, VoucherInfo>();
            List<VoucherInfo> vou_list = da.QueryListByDev(voucherInfo.OwnerID, voucherInfo.DeviceID, voucherInfo.projectID);
            if (vou_list != null)
            {
                vouvher_dic = vou_list.ToDictionary(key => key.OwnerID, value => value);

                //副卡循环更新凭证
                foreach (var item in list)
                {
                    bool result = LoopVoucher(vouvher_dic, item.ID, voucherInfo);

                    if (!result)
                    {
                        message.errcode = 1;
                        message.errmsg = "凭证新增失败";
                        return message;
                    }
                }
            }
            //主卡更新凭证
            bool result1 = LoopVoucher(vouvher_dic, voucherInfo.OwnerID, voucherInfo);
            if (!result1)
            {
                message.errcode = 1;
                message.errmsg = "凭证新增失败";
            }

            return message;
        }

        public static async Task<bool> SavePerson(VoucherInfo voucherInfo, string wwwroot, string phyfloor)
        {
            SavePersonInfo savePersonInfo = new SavePersonInfo();
            savePersonInfo.method = "savePerson";
            Random random = new Random();
            savePersonInfo.req_id = random.Next();
            SavePersonData savePersonData = new SavePersonData();
            List<SavePersonInfoData> person_list = new List<SavePersonInfoData>();
            SavePersonInfoData savePerson = new SavePersonInfoData();
            savePerson.personID = voucherInfo.UUID;
            savePerson.startTime = Convert.ToDateTime(voucherInfo.EffectiveStarttime).ToString("yyyy-MM-dd HH:mm:ss");
            savePerson.endTime = Convert.ToDateTime(voucherInfo.EffectiveEndtime).ToString("yyyy-MM-dd HH:mm:ss");
            savePerson.sex = 0;
            savePerson.personType = voucherInfo.OwnerType == 2 ? 1 : voucherInfo.OwnerType == 4 ? 2 : 0;
            savePerson.cardNo = voucherInfo.CardNO;
            savePerson.personName = voucherInfo.OwnerName;
            string url = wwwroot + "/wwwroot" + voucherInfo.PicturePath;
            savePerson.personPhoto = PicToBase64String(url);
            if (savePerson.personType == 2)
            {
                savePerson.backFloor = "FFFFFFFFFFFFFFFF";
                savePerson.frontFloor = "FFFFFFFFFFFFFFFF";
            }
            else
            {
                string floor = GetFloorCmd(phyfloor);
                savePerson.backFloor = floor;
                savePerson.frontFloor = floor;
            }
            person_list.Add(savePerson);
            savePersonData.personInfos = person_list;

            List<SavePersonDeviceData> device_list = new List<SavePersonDeviceData>();
            SavePersonDeviceData savedevice = new SavePersonDeviceData();
            savedevice.deviceID = voucherInfo.DeviceNO;
            savedevice.deviceName = voucherInfo.DeviceName;
            device_list.Add(savedevice);
            savePersonData.deviceInfos = device_list;
            savePersonInfo.data = savePersonData;

            string Msg = JsonConvert.SerializeObject(savePersonInfo);

            //await DeviceWebSocketMiddleware.SendMsg(Msg);
            await DeviceWebSocketMiddleware.NewSendMsg(Msg);
            return true;
        }

        public static async Task<bool> DeletePerson(VoucherInfo voucherInfo)
        {
            DeletePersonInfo deletePersonInfo = new DeletePersonInfo();
            deletePersonInfo.method = "delPerson";
            DeletePersonData deletePersonData = new DeletePersonData();
            List<DeletePersonInfoData> person_list = new List<DeletePersonInfoData>();
            DeletePersonInfoData personInfoData = new DeletePersonInfoData();
            personInfoData.personID = voucherInfo.UUID;
            person_list.Add(personInfoData);
            List<SavePersonDeviceData> device_list = new List<SavePersonDeviceData>();
            SavePersonDeviceData savePersonDevice = new SavePersonDeviceData();
            savePersonDevice.deviceID = voucherInfo.DeviceNO;
            savePersonDevice.deviceName = voucherInfo.DeviceName;
            device_list.Add(savePersonDevice);
            deletePersonData.personInfos = person_list;
            deletePersonData.deviceInfos = device_list;
            deletePersonInfo.data = deletePersonData;
            Random random = new Random();
            deletePersonInfo.req_id = random.Next();
            string Msg = JsonConvert.SerializeObject(deletePersonInfo);

            //await DeviceWebSocketMiddleware.SendMsg(Msg);
            await DeviceWebSocketMiddleware.NewSendMsg(Msg);
            return true;
        }

        public static async Task<bool> BatchDeletePerson(List<JLLssueinfoDelBatchPerson> voucher_list, DeviceInfo deviceInfo)
        {
            DeletePersonInfo deletePersonInfo = new DeletePersonInfo();
            deletePersonInfo.method = "delPerson";
            DeletePersonData deletePersonData = new DeletePersonData();
            List<DeletePersonInfoData> person_list = new List<DeletePersonInfoData>();
            foreach (var item in voucher_list)
            {
                DeletePersonInfoData personInfoData = new DeletePersonInfoData();
                personInfoData.personID = item.PersonId;
                person_list.Add(personInfoData);
            }

            List<SavePersonDeviceData> device_list = new List<SavePersonDeviceData>();
            SavePersonDeviceData savePersonDevice = new SavePersonDeviceData();
            savePersonDevice.deviceID = deviceInfo.DeviceNO;
            savePersonDevice.deviceName = deviceInfo.DeviceName;
            device_list.Add(savePersonDevice);
            deletePersonData.personInfos = person_list;
            deletePersonData.deviceInfos = device_list;
            deletePersonInfo.data = deletePersonData;
            Random random = new Random();
            deletePersonInfo.req_id = random.Next();
            string Msg = JsonConvert.SerializeObject(deletePersonInfo);

            //await DeviceWebSocketMiddleware.SendMsg(Msg);
            await DeviceWebSocketMiddleware.NewSendMsg(Msg);
            return true;
        }

        public static async Task<bool> ClearPerson(DeviceInfo deviceInfo)
        {
            ClearPersonInfo clearPersonInfo = new ClearPersonInfo();
            List<SavePersonDeviceData> list = new List<SavePersonDeviceData>();
            SavePersonDeviceData savePersonDeviceData = new SavePersonDeviceData();
            savePersonDeviceData.deviceID = deviceInfo.DeviceNO;
            savePersonDeviceData.deviceName = deviceInfo.DeviceName;
            list.Add(savePersonDeviceData);
            clearPersonInfo.data = list;
            clearPersonInfo.method = "clearPerson";
            Random random = new Random();
            clearPersonInfo.req_id = random.Next();
            string Msg = JsonConvert.SerializeObject(clearPersonInfo);

            //await DeviceWebSocketMiddleware.SendMsg(Msg);
            await DeviceWebSocketMiddleware.NewSendMsg(Msg);
            return true;
        }

        public static string GetFloorCmd(string Pfloor)
        {
            if (Pfloor == "")
            {
                return "";
            }
            else
            {
                string DefaultFloor = "";
                string updateFloorTOHex = "";
                string[] strArray = Pfloor.Split(',');
                string dd;
                for (int i = 1; i <= 64; i++)
                {
                    DefaultFloor = DefaultFloor + "0";
                }
                for (int j = 0; j < strArray.Length; j++)
                {

                    DefaultFloor = DefaultFloor.Remove(64 - Convert.ToInt32(strArray[j]), 1).Insert(64 - Convert.ToInt32(strArray[j]), "1");
                }
                string updateFloor = DefaultFloor.Substring(0, 16) + DefaultFloor.Substring(16, 16) + DefaultFloor.Substring(32, 16) + DefaultFloor.Substring(48, 16);
                for (int k = 0; k < 64; k += 8)
                {
                    updateFloorTOHex = updateFloorTOHex + string.Format("{0:X}", Convert.ToInt32(updateFloor.Substring(k, 8), 2)).PadLeft(2, '0');
                }
                return updateFloorTOHex;
            }
        }

        public string SortFloor(string AuthorizedFloor, string FloorInfo, string pFloorInfo)
        {
            string floor = string.Empty;
            string[] datas = AuthorizedFloor.Split(',');
            string[] array = FloorInfo.Split(',');
            string[] pfloor_array = pFloorInfo.Split(',');
            foreach (string value in datas)
            {
                int index = array.ToList().IndexOf(value);
                if (index >= 0)
                {
                    floor += pfloor_array[index] + ",";
                }
            }
            if (!string.IsNullOrEmpty(floor))
            {
                floor = floor.TrimEnd(',');
            }
            return floor;
        }

        public bool LoopVoucher(Dictionary<int, VoucherInfo> vouvher_dic, int ownerid, VoucherInfo voucherInfo)
        {
            VoucherInfo info;
            VoucherDAL da = new VoucherDAL();
            bool result;
            VoucherInfo voucher = new VoucherInfo();
            if (vouvher_dic.TryGetValue(ownerid, out info))
            {
                voucher.ID = voucherInfo.ID;
                voucher.OwnerID = ownerid;
                voucher.DeviceID = info.DeviceID;
                voucher.PicShow = info.PicShow;
                voucher.CardShow = info.CardShow;
                voucher.EffectiveStarttime = voucherInfo.EffectiveStarttime;
                voucher.EffectiveEndtime = voucherInfo.EffectiveEndtime;
                voucher.PicuploadFlag = info.PicuploadFlag;
                voucher.CarduploadFlag = info.CarduploadFlag;
                voucher.Lssuestate = info.Lssuestate;
                voucher.CardNO = info.CardNO;
                voucher.PicturePath = info.PicturePath;
                voucher.AuthorizedFloor = voucherInfo.AuthorizedFloor;
                voucher.AuthData = voucherInfo.AuthData;
                voucher.QRCodeFlag = voucherInfo.QRCodeFlag;
                DateTime starttime1 = Convert.ToDateTime(info.EffectiveStarttime);
                DateTime starttime2 = Convert.ToDateTime(voucherInfo.EffectiveStarttime);
                DateTime endtime1 = Convert.ToDateTime(info.EffectiveEndtime);
                DateTime endtime2 = Convert.ToDateTime(voucherInfo.EffectiveEndtime);
                if (info.AuthorizedFloor != voucherInfo.AuthorizedFloor)
                {
                    voucher.Lssuestate = 0;
                    voucher.SyncFlag = 0;
                }
                else if (DateTime.Compare(starttime1, starttime2) != 0 || DateTime.Compare(endtime1, endtime2) != 0)
                {
                    voucher.Lssuestate = 0;
                    voucher.SyncFlag = 0;
                }

                result = da.UpdateVoucherByDev(voucher);
            }
            else
            {
                voucher.OwnerID = ownerid;
                voucher.DeviceID = voucherInfo.DeviceID;
                voucher.AuthorizedFloor = voucherInfo.AuthorizedFloor;
                voucher.EffectiveStarttime = voucherInfo.EffectiveStarttime;
                voucher.EffectiveEndtime = voucherInfo.EffectiveEndtime;
                voucher.PicShow = voucherInfo.PicShow;
                voucher.CardShow = voucherInfo.CardShow;
                voucher.AuthorizedFloor = voucherInfo.AuthorizedFloor;
                voucher.projectID = voucherInfo.projectID;
                voucher.AuthData = voucherInfo.AuthData;
                voucher.QRCodeFlag = voucherInfo.QRCodeFlag;
                result = da.AddVoucher(voucher);
            }
            return result;
        }

        public ResponseMessage DelVoucher(VoucherInfo voucherInfo)
        {
            ResponseMessage message = new ResponseMessage();
            if (voucherInfo.Lssuestate==0)
            {
                VoucherDAL voucherDAL = new VoucherDAL();
                bool result = voucherDAL.DeleteVoucher(voucherInfo);
                if (result)
                {
                    message.errcode = 0;
                    message.errmsg = "删除凭证成功";
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "删除凭证失败";
                }
            }
            else
            {
                Task<bool> socket_result = DeletePerson(voucherInfo);
                if (socket_result.Result)
                {
                    message.errcode = 0;
                    message.errmsg = "删除凭证成功";
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "删除凭证失败";
                }
            }
          

            return message;
        }

        public ResponseMessage QueryVoucher(VoucherInfo voucherInfo)
        {
            ResponseMessage message = new ResponseMessage();

            VoucherDAL da = new VoucherDAL();
            message.errcode = 0;
            message.data = da.QueryVoucherList(voucherInfo);
            message.total = da.QueryVoucherListCount(voucherInfo);

            return message;
        }

        public ResponseMessage LoadVoucher(VoucherInfo voucherInfo)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherDAL da = new VoucherDAL();
            message.errcode = 0;
            message.data = da.LoadVoucher(voucherInfo.ID);

            return message;
        }

        public int GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt32(ts.TotalSeconds);
        }

        private static string PicToBase64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.ToString());
                return "";
            }
        }

        public ResponseMessage ClearVoucher(int deviceid, int personIdentity)
        {
            ResponseMessage message = new ResponseMessage();

            DeviceDAL deviceDAL = new DeviceDAL();
            DeviceInfo deviceInfo = deviceDAL.LoadDeviceInfo(deviceid);
            Task<bool> socket_result = ClearPerson(deviceInfo);
            if (socket_result.Result)
            {
                message.errcode = 0;
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "清空凭证失败";
            }

            return message;
        }

        public ResponseMessage DeleteBatchVoucher(List<JLLssueinfoDelBatchPerson> list, int deviceid)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherDAL da = new VoucherDAL();
            DeviceDAL deviceDAL = new DeviceDAL();
            DeviceInfo deviceInfo = deviceDAL.LoadDeviceInfo(deviceid);
            Task<bool> socket_result = BatchDeletePerson(list, deviceInfo);
            if (socket_result.Result)
            {
                message.errcode = 0;
                message.errmsg = "批量删除成功";
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "批量删除失败";
            }


            return message;
        }

        public ResponseMessage JLVoucherClearAll(int deviceid, int personIdentity)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherBUS BUS = new VoucherBUS();

            message = BUS.ClearVoucher(deviceid, personIdentity);

            return message;
        }

        public string HttpClientPost(string url, object datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }

        public ResponseMessage AddProVoucher(OwnerDeviceVoucher ownerDevice)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherDAL dAL = new VoucherDAL();
            VoucherInfo voucher1 = new VoucherInfo();
            voucher1.OwnerID = ownerDevice.OwnerInfo.ID;
            List<VoucherInfo> list = dAL.QueryExistVoucher(voucher1);
            foreach (var item in ownerDevice.DeviceVoucher_List)
            {
                ModbusRtu modbus = new ModbusRtu();
                VoucherDAL voucherDAL = new VoucherDAL();
                VoucherInfo voucher = new VoucherInfo();
                voucher.OwnerID = ownerDevice.OwnerInfo.ID;
                voucher.AuthorizedFloor = item.FloorInfo;
                if (ownerDevice.OwnerInfo.VirtualCard == 2)//梯控卡-开
                {
                    voucher.AuthData = modbus.GetLiftStateCmd(1);
                    voucher.EffectiveEndtime = Convert.ToDateTime("2038-01-01").ToString("yyyy-MM-dd HH:mm:ss");
                }
                else if (ownerDevice.OwnerInfo.VirtualCard == 3)//梯控卡-关
                {
                    voucher.AuthData = modbus.GetLiftStateCmd(0);
                    voucher.EffectiveEndtime = Convert.ToDateTime("2038-01-01").ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    voucher.AuthData = modbus.GetCallAdminCmd(ownerDevice.OwnerInfo.UUID);
                    voucher.EffectiveEndtime = Convert.ToDateTime(ownerDevice.OwnerInfo.MaxTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                voucher.projectID = ownerDevice.OwnerInfo.projectID;
                voucher.DeviceID = item.DeviceID;
                voucher.EffectiveStarttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                if (list.Exists(t => t.DeviceID == item.DeviceID))
                {
                    voucherDAL.UpdateVoucherByDev(voucher);
                }
                else
                {
                    voucherDAL.AddVoucher(voucher);
                }
            }
            return message;
        }

        public ResponseMessage JLVoucherIssue(int id, string deviceip, string path)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherBUS BUS = new VoucherBUS();
            VoucherDAL da = new VoucherDAL();
            VoucherInfo voucher = da.LoadVoucher(id);
          
            if (voucher.VirtualCard == 1 && string.IsNullOrEmpty(voucher.PicturePath))
            {
                message.errcode = 1;
                message.errmsg = "人脸和卡信息都为空，下发失败";
            }
            else
            {
                string phyfloor = SortFloor(voucher.AuthorizedFloor, voucher.FloorInfo, voucher.pFloorInfo);
                Task<bool> socket_result = SavePerson(voucher, path, phyfloor);
                if (socket_result.Result)
                {
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 0;

                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "凭证下发失败";
                }
            }
            return message;
        }

        public ResponseMessage OneClickVoucherIssue(ProVoucherInfo proVoucher, string path)
        {
            ResponseMessage message = new ResponseMessage();
            string failinfo = string.Empty;
            foreach (var item in proVoucher.Vouchers_List)
            {
                try
                {
                    if (item.DeviceState == "在线")
                    {

                        string phyfloor = SortFloor(item.AuthorizedFloor, item.FloorInfo, item.pFloorInfo);
                        Task<bool> socket_result = SavePerson(item, path, phyfloor);
                        if (socket_result.Result)
                        {
                            failinfo += item.DeviceName + ",";
                        }
                    }
                    else
                    {
                        failinfo += item.DeviceName + ",";
                    }
                }
                catch
                {
                    continue;
                }
            }
            if (failinfo.Length > 0)
            {
                message.errcode = 1;
                message.errmsg = "设备" + failinfo.Substring(0, failinfo.Length - 1) + "下发失败";
            }
            else
            {
                message.errcode = 0;
            }
            return message;
        }

        public ResponseMessage OneClickVoucherDel(ProVoucherInfo proVoucher)
        {
            ResponseMessage message = new ResponseMessage();
            string failinfo = string.Empty;
            foreach (var item in proVoucher.Vouchers_List)
            {
                try
                {
                    if (item.DeviceState == "在线")
                    {
                        message = DelVoucher(item);
                    }
                    else
                    {
                        failinfo += item.DeviceName + ",";
                    }
                }
                catch
                {
                    continue;
                }
            }
            if (failinfo.Length > 0)
            {
                message.errcode = 1;
                message.errmsg = "设备" + failinfo.Substring(0, failinfo.Length - 1) + "删除失败";
            }
            else
            {
                message.errcode = 0;
            }
            return message;
        }

        public bool ImportVoucher(VoucherInfo voucher)
        {
            ModbusRtu modbus = new ModbusRtu();
            if (voucher.OwnerType == 2)
            {
                voucher.AuthData = modbus.GetCallAdminCmd(voucher.UUID);
            }
            else
            {
                string phyfloor = SortFloor(voucher.AuthorizedFloor, voucher.FloorInfo, voucher.pFloorInfo);
                voucher.AuthData = modbus.GetCallCmd(phyfloor, voucher.UUID);
            }
            VoucherDAL voucherDAL = new VoucherDAL();
            bool result = voucherDAL.AddVoucher(voucher);

            return result;
        }

        public void SyncQRCodeVoucher(VoucherInfo voucherInfo)
        {
            try
            {
                OwnerDAL ownerDAL = new OwnerDAL();
                int auditid = ownerDAL.QueryAuditId(voucherInfo.OwnerID, voucherInfo.projectID);
                QRCodeVoucherInfo qRCodeVoucherInfo = new QRCodeVoucherInfo();
                qRCodeVoucherInfo.ProjectKey = voucherInfo.project_key;
                qRCodeVoucherInfo.method = "UpdateAudit";
                List<QRCodeVoucherInfoData> qRCodeVoucherInfoDatas = new List<QRCodeVoucherInfoData>();
                QRCodeVoucherInfoData codeVoucherInfoData = new QRCodeVoucherInfoData();
                codeVoucherInfoData.auditid = auditid;
                codeVoucherInfoData.deviceName = voucherInfo.DeviceName;
                codeVoucherInfoData.deviceNo = voucherInfo.DeviceNO;

                List<QRCodeVoucherInfoFloorInfo> floor_list = new List<QRCodeVoucherInfoFloorInfo>();
                string[] dfloors = voucherInfo.AuthorizedFloor.Split(',');
                string[] array = voucherInfo.FloorInfo.Split(',');
                string[] pfloors = voucherInfo.pFloorInfo.Split(',');
                foreach (var value in dfloors)
                {
                    QRCodeVoucherInfoFloorInfo qRCodeVoucherInfoData = new QRCodeVoucherInfoFloorInfo();
                    qRCodeVoucherInfoData.startTime = voucherInfo.EffectiveStarttime;
                    qRCodeVoucherInfoData.endTime = voucherInfo.EffectiveEndtime;
                    qRCodeVoucherInfoData.dfloor = value;
                    int index = array.ToList().IndexOf(value);
                    if (index >= 0)
                    {
                        int pfloor = Convert.ToInt32(pfloors[index]);
                        string data = GetCallCmd(pfloor, voucherInfo.LadderID);
                        qRCodeVoucherInfoData.pfloor = pfloor;
                        qRCodeVoucherInfoData.qrcodeData = data;
                    }
                    floor_list.Add(qRCodeVoucherInfoData);
                }
                codeVoucherInfoData.floor = floor_list;
                qRCodeVoucherInfoDatas.Add(codeVoucherInfoData);
                qRCodeVoucherInfo.data = qRCodeVoucherInfoDatas;
                string re = HttpClientPost(voucherInfo.server_addr + "/api/Request/UpdateAudit", qRCodeVoucherInfo);
                QRCodeVoucherInfoReturn qRCodeReturn = JsonConvert.DeserializeObject<QRCodeVoucherInfoReturn>(re);
                if (qRCodeReturn != null && qRCodeReturn.code == 0 && qRCodeReturn.method == "UpdateAudit")
                {
                    VoucherDAL voucherDAL = new VoucherDAL();
                    foreach (var item in qRCodeReturn.data)
                    {
                        bool result = voucherDAL.UpdateQRCodeSyncFlag(item);
                    }
                }
            }
            catch(Exception ex)
            {
                LogHelper.Log(ex.ToString());
            }

        }

        public string GetCallCmd(int Pfloor, string ladderid)
        {
            string DefaultFloor = "";
            string updateFloorTOHex = "";
            string dd;
            for (int i = 1; i <= 80; i++)
            {
                DefaultFloor = DefaultFloor + "0";
            }
            DefaultFloor = DefaultFloor.Remove(80 - Pfloor, 1).Insert(80 - Pfloor, "1");
            string updateFloor = DefaultFloor.Substring(64, 16) + DefaultFloor.Substring(48, 16) + DefaultFloor.Substring(32, 16) + DefaultFloor.Substring(16, 16) + DefaultFloor.Substring(0, 16);
            for (int k = 0; k < 80; k += 8)
            {
                updateFloorTOHex = updateFloorTOHex + string.Format("{0:X}", Convert.ToInt32(updateFloor.Substring(k, 8), 2)).PadLeft(2, '0');
            }
            //楼层点亮
            dd = "008B0000001B" + Convert.ToInt32(ladderid).ToString("X").PadLeft(2, '0') + "100019000A14" + updateFloorTOHex + "00000000000000000000";
            return dd;
        }

        public void DeleteQRCodeVoucher(VoucherInfo voucherInfo)
        {
            try
            {
                OwnerDAL ownerDAL = new OwnerDAL();
                int auditid = ownerDAL.QueryAuditId(voucherInfo.OwnerID, voucherInfo.projectID);
                QRCodeVoucherInfo qRCodeVoucherInfo = new QRCodeVoucherInfo();
                qRCodeVoucherInfo.ProjectKey = voucherInfo.project_key;
                qRCodeVoucherInfo.method = "DeleteVoucher";
                List<QRCodeVoucherInfoData> qRCodeVoucherInfoDatas = new List<QRCodeVoucherInfoData>();
                QRCodeVoucherInfoData codeVoucherInfoData = new QRCodeVoucherInfoData();
                codeVoucherInfoData.auditid = auditid;
                codeVoucherInfoData.deviceName = voucherInfo.DeviceName;
                codeVoucherInfoData.deviceNo = voucherInfo.DeviceNO;

                List<QRCodeVoucherInfoFloorInfo> floor_list = new List<QRCodeVoucherInfoFloorInfo>();
                qRCodeVoucherInfoDatas.Add(codeVoucherInfoData);
                qRCodeVoucherInfo.data = qRCodeVoucherInfoDatas;
                string re = HttpClientPost(voucherInfo.server_addr + "/api/Request/DeleteVoucher", qRCodeVoucherInfo);
            }
            catch
            {

            }
        }
    }
}